#include"tcp_client.hpp"
#include<time.h>

static void usage(string proc)
{
    cout<<"Usage:\n\t"<< proc <<" port\n"<<endl;
}




//./udp_client ip  port
int main(int argc ,char * argv[])
{
    if(argc!=3)
    {
        usage(argv[0]);
        exit(USING_ERR);
    }
    string serverip=argv[1];  
    uint16_t serverport =atoi(argv[2]);

    int sock=socket(AF_INET,SOCK_STREAM,0); //有链接安全可靠协议
    if(sock<0)
    {
        cerr<<"创建 socker 失败: "<<strerror(errno)<<endl;
        exit(SOCKER_ERR);
    }
    

    //明确 serverip serverport
    struct sockaddr_in server;
    memset(&server,0,sizeof(server));
    server.sin_family=AF_INET;//ip4
    server.sin_port=htons(serverport);//主机转网络
    inet_aton(serverip.c_str(),&server.sin_addr);


    int k=3;
    while(connect(sock,(struct sockaddr*)&server,sizeof(server)) != 0)
    {
        sleep(1);

        cout<<"正在重新连接" << k--<<endl;

        if(k<=0) 
        {
           break;
        }
    }

    if(k<=0)
    {
        cerr<<"连接失败"<<endl;
        exit(CONNECT_ERR);
    }

    char buf[256];

    while(true)
    {
        string line;
        cout<<"sendto>>> "<<endl;
        getline(cin,line);
        write(sock,line.c_str(),line.size());

        ssize_t s=read(sock,buf,sizeof(buf)-1);
        if(s>0)
        {
            buf[s]=0;
            cout<<"[sendto>>>]"<<s<<endl;
        }
        else if(s==0)
        {
            cerr<<"quite"<<endl;
            break;

        }
        else
        {
            cerr <<"read error: "<<strerror(errno)<<"or client quite"<<endl;
            break;

        }



    }
    close(sock);

    


    return 0;
}